package util.udp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;

public class UDPClient extends Thread {
	
	private String ip;
	
	private int port;
	
	private byte[] requestData;
	
	private Callback callback;
	
	public UDPClient(String ip, int port, byte[] requestData,Callback callback) {
		this.ip = ip;
		this.port = port;
		this.requestData = requestData;
		this.callback = callback;
	}

	@Override
	public void run() {
		try (DatagramSocket socket = new DatagramSocket()) {
			InetAddress address = InetAddress.getByName(ip);
			// 1.创建数据报，包含发送的数据信息
			DatagramPacket requestPacket = new DatagramPacket(requestData, requestData.length, address, port);
			// 2.向服务端发送数据报
			socket.send(requestPacket);
			
			// 1.创建数据报，用于接收服务端的信息
			byte[] responseData = new byte[1024];
			DatagramPacket responsePacket = new DatagramPacket(responseData,responseData.length);
			// 2.接收服务端的信息
			socket.setSoTimeout(5000);
			socket.receive(responsePacket); // 在接收到响应之前，次方法会一直处于阻塞状态
			// 3.读取信息
			String reply = new String(responseData,0,responsePacket.getLength());
			if(this.callback != null) {
				callback.callback(reply);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (SocketTimeoutException e) {
			throw new RuntimeException("连接超时");
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		/*byte[] datas = new byte[] {(byte) 0xCE,0x30,0x00,0x44,(byte) 0x80,
				(byte) 0xA6,(byte) 0xCE,0x7B,0x6D,0x61,
				0x67,0x69,0x63,0x3A,0x22,
				0x41,0x54,0x52,0x43,0x22,
				0x2C,0x73,0x65,0x71,0x3A,
				0x35,0x2C,0x64,0x63,0x6C,
				0x61,0x73,0x73,0x3A,0x33,
				0x32,0x2C,0x64,0x73,0x75,
				0x62,0x3A,0x31,0x36,0x2C,
				0x62,0x6F,0x64,0x79,0x3A,
				0x7B,0x22,0x6B,0x65,0x79,
				0x22,0x3A,0x22,0x62,0x61,
				0x74,0x74,0x65,0x72,0x79,
				0x5F,0x73,0x74,0x61,0x74,
				0x75,0x73,0x22,0x7D,0x7D,
				0x0D,0x0A,(byte) 0xCE};*/
		byte[] datas = new byte[] {(byte) 0xCE,0x30,0x00,0x4D,(byte) 0x80,(byte) 0xA6,
				(byte) 0xCE,0x7B,0x6D,0x61,0x67,0x69,
				0x63,0x3A,0x22,0x41,0x54,0x52,
				0x43,0x22,0x2C,0x73,0x65,0x71,
				0x3A,0x34,0x2C,0x64,0x63,0x6C,
				0x61,0x73,0x73,0x3A,0x31,0x36,
				0x2C,0x64,0x73,0x75,0x62,0x3A,
				0x31,0x31,0x32,0x2C,0x62,0x6F,
				0x64,0x79,0x3A,0x7B,0x22,0x73,
				0x69,0x6D,0x5F,0x69,0x64,0x22,
				0x3A,0x22,0x31,0x22,0x2C,0x22,
				0x6E,0x75,0x6D,0x62,0x65,0x72,
				0x22,0x3A,0x22,0x31,0x32,0x33,
				0x34,0x35,0x36,0x22,0x7D,0x7D,
				0x0D,0x0A,(byte) 0xCE};
		try {
			UDPClient client = new UDPClient("192.168.54.1",20000,datas,new Callback() {
				
				@Override
				public void callback(String reply) {
					System.out.println("ret：" + reply);
				}
			});
			client.start();
		} catch (Exception e) {
			System.out.println("连接超时");
		}
	}
}
